<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>智能对话助手</h2>
      <el-button type="primary" size="mini" @click="clearChat">清空对话</el-button>
    </div>
    
    <div class="chat-messages" ref="messageContainer">
      <!-- 系统提示 -->
      <div class="system-message">
        我是GGBao，一个乐于助人的助手。有什么问题我可以帮助你吗？
      </div>
      
      <!-- 对话消息列表 -->
      <div v-for="(msg, index) in messages" :key="index" :class="['message-item', msg.role]">
        <div class="avatar">
          <el-avatar :icon="msg.role === 'user' ? User : ChatRound" />
        </div>
        <div class="content">{{ msg.content }}</div>
      </div>
      
      <!-- 加载中状态 -->
      <div v-if="loading" class="message-item assistant loading">
        <div class="avatar">
          <el-avatar :icon="ChatRound" />
        </div>
        <div class="content">
          <el-skeleton active :rows="3" style="width: 300px;"></el-skeleton>
        </div>
      </div>
    </div>
    
    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="userInput"
        placeholder="请输入消息..."
        @keyup.enter="sendMessage"
        clearable
      />
      <el-button type="primary" @click="sendMessage" :disabled="!userInput || loading">
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { User, ChatRound } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { sendChatMessage, clearChatHistory } from '@/api/chatInterface/ChatInterface';

// 对话消息列表
const messages = ref([]);
// 用户输入
const userInput = ref('');
// 加载状态
const loading = ref(false);
// 消息容器引用
const messageContainer = ref(null);

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom();
});

// 组件挂载时滚动到底部
onMounted(() => {
  scrollToBottom();
});

// 滚动到最新消息
const scrollToBottom = () => {
  setTimeout(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  }, 100);
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return;
  
  const content = userInput.value.trim();
  // 添加用户消息到列表
  messages.value.push({ role: 'user', content });
  userInput.value = '';
  loading.value = true;
  
  try {
    // 调用后端API
    const response = await sendChatMessage(content);
    // 关键修复：从msg字段获取内容（根据实际接口响应调整）
    if (response.code === 200 && response.msg) {
      // 添加助手回复到列表
      messages.value.push({ 
        role: 'assistant', 
        content: response.msg  // 这里从msg字段获取内容
      });
    } else {
      ElMessage.error('获取回复失败：' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('发送消息失败', error);
    ElMessage.error('发送消息失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 清空对话
const clearChat = async () => {
  try {
    await clearChatHistory();
    messages.value = [];
    ElMessage.success('对话已清空');
  } catch (error) {
    console.error('清空对话失败', error);
    ElMessage.error('清空对话失败，请稍后重试');
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #ffffff;
}

.system-message {
  text-align: center;
  color: #64748b;
  font-size: 14px;
  margin-bottom: 16px;
  padding: 8px 16px;
  background-color: #f1f5f9;
  border-radius: 16px;
  display: inline-block;
  align-self: center;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  max-width: 80%;
}

.message-item.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.avatar {
  margin-right: 12px;
  margin-top: 4px;
}

.message-item.user .avatar {
  margin-right: 0;
  margin-left: 12px;
}

.content {
  padding: 10px 16px;
  border-radius: 18px;
  line-height: 1.5;
  word-break: break-word;
}

.message-item.user .content {
  background-color: #4096ff;
  color: white;
}

.message-item.assistant .content {
  background-color: #f1f5f9;
  color: #1e293b;
}

.loading .content {
  background-color: #f8fafc;
}

.chat-input {
  display: flex;
  gap: 8px;
  padding: 16px;
  border-top: 1px solid #e5e7eb;
  background-color: #f8fafc;
}

.chat-input .el-input {
  flex: 1;
}
</style>
